<template>
  <div class="service-order">
    <tags :labels="labels" :current-label="currentLabel" @clickLabel="clickLabel" class="tag">
      <ul class="list">
        <li
          v-for="(item, index) in list"
          :key="index"
          class="list-item border-bottom-1px"
        >
          <div class="time">
            <span class="text">下单时间:</span>
            <span class="value">{{ item.create_time }}</span>
          </div>
          <div class="sn">
            <span class="text">订单号:</span>
            <span class="value">{{ item.sn }}</span>
          </div>
          <ul class="item">
            <li
              v-for="(o, i) in item.item"
              :key="i"
            >
              <div class="image" v-if="o.product && o.product.mainImage">
                <img v-lazy="o.product.mainImage.thumbnail_path" />
              </div>
              <div class="desc" v-if="o.product">
                <p class="title">{{ o.product.title }}</p>
                <p class="quantity">数量: {{ o.quantity }}</p>
                <div class="pay">
                  <p class="price">价格: <span>{{ +o.price }}</span></p>
                  <p class="score" v-if="+o.score > 0">积分: <span>{{ +o.score }}</span></p>
                  <p class="freight" v-if="+o.freight > 0">运费: <span>{{ +o.freight }}</span></p>
                </div>
                <div class="express" v-if="o.logistics && o.logistics.company">
                  <p class="e">快递信息: {{o.logistics.company.name}} {{o.logistics.express_sn}}</p>
                  <p class="button" @click="$router.push(`/service/express/${o.logistics.id}`)">查看物流信息</p>
                  <p class="copyLogistics" @click="copyLogistics(o)">复制</p>
                </div>
              </div>
            </li>
          </ul>
          <div class="total-pay">
            总金额: <span>{{ +item.total_pay }}</span>
            <template v-if="+item.status === 0">
              现金需要支付: <span>￥{{ +item.use_money }}</span>
            </template>
          </div>
          <div class="address" v-if="item.address">
            <p class="nickname">收货人昵称: {{item.address.nickname}}</p>
            <p class="nickname">收货人电话: {{item.address.mobile}}</p>
            <p class="city">地区: {{ item.address | addressText }}</p>
            <p class="info">详细地址: {{ item.address.address }}</p>
          </div>
          <div class="active" v-if="item.active_list && item.active_list.length > 0">
            <div class="active_item" v-for="(a, i) in item.active_list" :key="i" @click="copyActive(a)">
              激活码{{i + 1}}:
              <span>{{a.active_code}}</span>
              <span class="color">{{+a.active_status >= 1 ? '已使用' : '未使用'}}</span>
              <span class="click">点击复制</span>
            </div>
          </div>
          <div class="status">
            <span class="text">状态:</span>
            <span class="value">{{ item.status | statusText }}</span>
          </div>
          <div class="ops" v-if="+item.status === 0" @click="uploadPay(item)">上传打款凭证</div>
          <div class="ops two" v-if="+item.status === 0" @click="resetPay(item)">去支付</div>
          <div class="ops" v-if="+item.status === 5" @click="remove(item)">删除</div>
          <div class="ops" v-if="item.active && item.active.length === 0 && +item.status === 1 && !item.disabled" @click="urge(item)">催单</div>
          <!--          <div class="ops" v-if="+item.status === 2 && false" @click="viewExpress(item)">查看物流</div>-->
          <div class="ops" v-if="+item.status === 2" @click="$router.push(`/service/express/${item.item[0].logistics.id}`)">查看物流</div>
          <div class="ops two" v-if="+item.status === 2" @click="confirmReceived(item)">确认收货</div>
          <div class="ops" v-if="+item.status === 3" @click="comment(item)">去评价</div>
          <div class="ops" v-if="+item.status === 4" @click="finish(item)">完成售后</div>
          <div class="ops two" v-if="+item.status === 3 || +item.status === 10" @click="service(item)">申请售后</div>
          <div class="cancel" v-if="+item.status === 0">
            <cube-button inline @click="cancel(item)">取消订单</cube-button>
          </div>
          <div class="aaa" v-if="false && !item.result && +item.active_ok === 0 && item.active && item.active.length > 0">
            <div class="k">
              <cube-input placeholder="输入激活码" v-model="item.code" />
            </div>
            <div class="btn">
              <cube-button primary @click="goActive(item)">激活</cube-button>
            </div>
          </div>
        </li>
      </ul>
      <pull-up
        :loading="loading"
        :busy="queryList.busy"
        @loadMore="loadMore" />
    </tags>
    <loading :show="loading" />
  </div>
</template>

<script>
import Tags from '../components/Tags'
import Loading from '@/components/Loading'
import api from '@/api'
import base64 from '@/util/base64'
import PullUp from '@/components/PullUp'
export default {
  name: 'ServiceOrder',
  components: {
    Tags,
    Loading,
    PullUp
  },
  filters: {
    addressText(v) {
      if (v && v.city) {
        return `${v.city.province} ${v.city.city} ${v.city.area} ${v.address} ${v.nickname} ${v.mobile}`
      }
      return ''
    },
    statusText(v) {
      // 待支付
      // 'NON_PAYMENT' => 0,
      //   // 已支付(待发货)
      //   'PAID' => 1,
      //   // 待收货
      //   'WAIT_RECEIVING' => 2,
      //   // 已收货(待评价)
      //   'RECEIVED' => 3,
      //   // 售后
      //   'SERVICE' => 4,
      //   // 取消
      //   'CANCEL' => 5,
      //   // 完成
      //   'FINISH' => 10,
      switch (+v) {
        case 0:
          return '待支付'
        case 1:
          return '待发货'
        case 2:
          return '待收货'
        case 3:
          return '待评价'
        case 4:
          return '售后中'
        case 5:
          return '已取消'
        case 6:
          return '已退款'
        case 10:
          return '已完成'
      }
    }
  },
  computed: {
    currentLabel() {
      return this.labels[this.current]
    }
  },
  data() {
    return {
      labels: [],
      current: 0,
      list: [],
      loading: false,
      queryList: {}
    }
  },
  methods: {
    copyActive(active) {
      // 创建输入框元素
      const oInput = document.createElement('input')
      // 将想要复制的值
      oInput.value = active.active_code
      // 页面底部追加输入框
      document.body.appendChild(oInput)
      // 选中输入框
      oInput.select()
      // 执行浏览器复制命令
      document.execCommand('Copy')
      // 弹出复制成功信息
      this.$createToast({
        type: 'correct',
        time: 500,
        txt: '复制成功'
      }).show()
      // 复制后移除输入框
      oInput.remove()
    },
    copyLogistics(o) {
      if (!o.logistics) {
        return
      }
      // 创建输入框元素
      const oInput = document.createElement('input')
      // 将想要复制的值
      oInput.value = o.logistics.express_sn
      // 页面底部追加输入框
      document.body.appendChild(oInput)
      // 选中输入框
      oInput.select()
      // 执行浏览器复制命令
      document.execCommand('Copy')
      // 弹出复制成功信息
      this.$createToast({
        type: 'correct',
        time: 500,
        txt: '复制成功'
      }).show()
      // 复制后移除输入框
      oInput.remove()
    },
    // 激活码
    // getActiveList(row) {
    //   let list = []
    //   if (row.item) {
    //     row.item.forEach(x => {
    //       if (x.active0 && x.active0.length > 0) {
    //         list = [...list, ...x.active0]
    //       }
    //     })
    //   }
    //   // console.log(list)
    // },
    goActive(item) {
      if (!item.code) {
        return this.$createToast({
          type: 'error',
          time: 200,
          txt: '请输入激活码'
        }).show()
      }
      api.My.active({
        id: item.id,
        code: item.code
      }).then(() => {
        this.$set(item, 'result', true)
        return this.$createToast({
          time: 200,
          txt: '操作成功'
        }).show()
      })
    },
    loadMore() {
      setTimeout(() => {
        this.getList(true)
      }, 200)
    },
    getList(append = false) {
      if (this.queryList.busy === false) {
        this.queryList.page++
        this.loading = true
        this.queryList.busy = true
        api.My.orderList({
          ...this.queryList,
          status: this.current
        }).then(response => {
          let { data } = response
          data = base64.parse(data)
          if (data.list.length === 0) {
            this.queryList.busy = true
          } else {
            this.queryList.busy = false
            if (append) {
              this.list = this.list.concat(data.list)
            } else {
              this.list = data.list
            }
          }
          // console.log(this.list)
        }).finally(() => {
          this.loading = false
        })
      }
    },
    createTags () {
      /*
        // 待支付
        'NON_PAYMENT' => 0,
        // 已支付(待发货)
        'PAID' => 1,
        // 待收货
        'WAIT_RECEIVING' => 2,
        // 已收货(待评价)
        'RECEIVED' => 3,
        // 售后
        'SERVICE' => 4,
        // 取消
        'CANCEL' => 5,
        // 完成
        'FINISH' => 10,

        'ALL' => -1

       */
      const tags = []
      tags[0] = '全部'
      tags[1] = '已完成'
      tags[2] = '待付款'
      tags[3] = '待发货'
      tags[4] = '待收货'
      tags[5] = '待评价'
      tags[6] = '售后'
      tags[7] = '已取消'
      this.labels = tags
    },
    clickLabel(index) {
      this.current = index
      this.init()
      this.list = []
      this.getList()
    },
    init() {
      this.queryList = this.queryList = {
        page: 0,
        pageSize: 10,
        busy: false
      }
    },
    uploadPay(item) {
      this.$router.push(`/service/offline/${item.id}`)
    },
    cancel(item) {
      this.$createDialog({
        type: 'confirm',
        // icon: 'cubeic-alert',
        title: '确定要取消吗?',
        // content: '我是内容',
        confirmBtn: {
          text: '确定',
          active: true,
          disabled: false,
          href: 'javascript:;'
        },
        cancelBtn: {
          text: '再想想',
          active: false,
          disabled: false,
          href: 'javascript:;'
        },
        onConfirm: () => {
          if (!item.disabled) {
            this.loading = true
            this.$set(item, 'disabled', true)
            api.My.orderDelete({ order_id: item.id }).then(() => {
              this.$set(item, 'status', '-99')
              this.list = this.list.filter(x => x.id !== item.id)
              this.$createToast({
                type: 'correct',
                time: 1000,
                txt: '操作成功',
                onTimeout: () => {
                  // this.current = 1
                }
              }).show()
            }).catch(() => {
              this.$set(item, 'disabled', false)
            }).finally(() => {
              this.loading = false
            })
          }
        }
      }).show()
    },
    /**
     * reset pay
     */
    resetPay(item) {
      if (!item.disabled) {
        this.loading = true
        this.$set(item, 'disabled', true)
        api.My.orderResetPay({ order_id: item.id }).then(() => {
          const serial = {
            order_id: item.id
          }
          this.$router.push(`/pay/${base64.encode(serial)}`)
        }).catch(() => {
          this.$set(item, 'disabled', false)
        }).finally(() => {
          this.loading = false
        })
      }
    },
    /**
     * delete
     */
    remove(item) {
      if (!item.disabled) {
        this.loading = true
        this.$set(item, 'disabled', true)
        api.My.orderDelete({ order_id: item.id }).then(() => {
          this.$set(item, 'status', '-99')
          this.$createToast({
            type: 'correct',
            time: 1000,
            txt: '操作成功',
            onTimeout: () => {
              this.current = 0
            }
          }).show()
        }).catch(() => {
          this.$set(item, 'disabled', false)
        }).finally(() => {
          this.loading = false
        })
      }
    },
    /**
     * view express
     */
    viewExpress(item) {
      console.log(item)
      // this.$router.push(`/service/express/${item.id}`)
    },
    /**
     * confirm received
     */
    confirmReceived(item) {
      if (!item.disabled) {
        this.loading = true
        this.$set(item, 'disabled', true)
        api.My.orderConfirmReceived({ order_id: item.id }).then(() => {
          this.$set(item, 'status', '3')
          this.$createToast({
            type: 'correct',
            time: 1000,
            txt: '操作成功',
            onTimeout: () => {
              this.current = 4
            }
          }).show()
        }).catch(() => {
          this.$set(item, 'disabled', false)
        }).finally(() => {
          this.loading = false
        })
      }
    },
    /**
     * urge
     */
    urge(item) {
      if (!item.disabled) {
        this.loading = true
        this.$set(item, 'disabled', true)
        api.My.orderUrge({ order_id: item.id }).then(() => {
          this.$createToast({
            type: 'correct',
            time: 1000,
            txt: '催单成功'
          }).show()
        }).catch(() => {
          this.$set(item, 'disabled', false)
        }).finally(() => {
          this.loading = false
        })
      }
    },
    /**
     * service
     */
    service(item) {
      this.$createToast({
        type: 'correct',
        time: 1000,
        txt: '请联系客服'
      }).show()
    },
    /**
     * comment
     */
    comment(item) {
      // this.$createToast({
      //   type: 'correct',
      //   time: 1000,
      //   txt: '评价已经关闭'
      // }).show()
      this.$router.push(`/service/comment/${item.id}`)
    },
    /**
     * finish
     */
    finish(item) {
      if (!item.disabled) {
        this.loading = true
        this.$set(item, 'disabled', true)
        api.My.orderFinish({ order_id: item.id }).then(() => {
          this.$set(item, 'status', '10')
          this.$createToast({
            type: 'correct',
            time: 1000,
            txt: '操作成功',
            onTimeout: () => {
              this.current = 1
            }
          }).show()
        }).catch(() => {
          this.$set(item, 'disabled', false)
        }).finally(() => {
          this.loading = false
        })
      }
    }
  },
  created () {
    this.current = Number.parseInt(this.$route.params.type || 0)
    this.createTags()
    this.init()
    this.getList()
  },
  deactivated () {
    this.queryList.busy = true
  }
}
</script>

<style scoped lang="stylus">
.service-order
  background white
  padding-bottom 30px
  border-radius 10px
  .list
    padding-bottom 15px
    .list-item
      position relative
      padding 10px 0
      text-align left
      .express
        margin-bottom 10px
        position relative
        .copyLogistics
          display inline-block
          background red
          padding 1px 5px
          margin-left 10px
          color white
          border-radius 5px
        .button
          display inline-block
          background $main_color
          padding 2.5px 10px
          color white
          border-radius 5px
      .time, .sn, .status, .item, .address, .total-pay
        margin 10px 0
        .value
          margin-left 5px
      .total-pay
        span
          color red
          font-size 16px
          font-weight 700
      .time
        color #ccc
      .sn
        font-weight 700
        font-size 16px
        .value
          color red
      .item
        li
          margin 15px 0
          display flex
          .image
            width 80px
            padding 10px
          .desc
            flex 1
            p
              line-height 20px
              &.title
                font-size 14px
                font-weight 700
            .pay
              p
                span
                  color red
      .address
        p
          line-height 20px
      .status
        .value
          font-weight 700
          color red
          font-size 16px

      .ops
        background $main_color
        position absolute
        padding 7.5px 10px
        right 0
        bottom 20px
        border-radius 5px
        color white
        font-weight 700
        min-width 55px
        text-align center
        &.two
          right 100px
          background #ccc
          color #666

.cancel
  height 40px
  line-height 40px

.aaa
  padding-top 20px
  .btn
    padding-top 10px

// 激活码
.active_item
  padding 10px
  background #eee
  span
    margin-right 10px
    &.color
      color red
</style>
